<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/3
 * Time: 13:03
 */
defined('IN_TS') or die('Access Denied.');

$userid = intval($TS_USER['userid']);

$orderid = intval($_GET['orderid']);

$strOrder = $new['gift']->find('gift_users',array(
    'orderid'=>$orderid,
));

if($strOrder==''){
    tsNotice('订单不存在！');
}
$strGift = $new['gift']->find('gift',array('giftid'=>$strOrder['giftid']));
$price = $strOrder['money'];

$types = trim($_POST['types']);
$forpayid = intval($_GET['forpayid']);

if($forpayid){
    //已有单号
    $strPayUser = $new['gift'] ->find('pay_user',array('forpayid'=>$forpayid));
    if ($strPayUser['trade_status'] == "TRADE_SUCCESS") {
        tsNotice('该单已支付过！', '返回>>', tsUrl('pay'));
    }
    $payid = $strPayUser['payid'];
    $price = $strPayUser['price'];
    $types = trim($strPayUser['types']);
}else{
    //生成订单

        $arrData = array(
            'userid'=>$userid,
            'types'=>'weixin',
            'price'=>$price,
            'orderid'=>$orderid,
            'addtime'=>time(),
        );
        $payid = $new['gift']->create('pay_user',$arrData);
        $forpayid = $payid + $arrData['addtime'];
        $new['gift']->update('pay_user',array(
            'payid'=>$payid
        ),array(
            'forpayid'=>$forpayid
        ));


}

/*
 * 微信支付
 */
if($types=='weixin'){


    $price2 = str_replace('.','',$price);
    $price2 = $price2*10;

    require_once "WxpayAPI_php_v3/lib/WxPay.Api.php";
    require_once "WxpayAPI_php_v3/example/WxPay.NativePay.php";
    require_once 'WxpayAPI_php_v3/example/log.php';
    $notify = new NativePay();
    $input = new WxPayUnifiedOrder();
    #$input->SetBody($_SERVER['HTTP_HOST'].$forpayid.'userid'.$userid.'price'.$price.'articleid'.$articleid);
    $input->SetBody('支付《'.$strGift['title'].'》');
    $input->SetAttach($forpayid.'|'.$orderid);
    $input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
    $input->SetTotal_fee($price2);
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 6000));
    $input->SetGoods_tag("test");
    $input->SetNotify_url(SITE_URL."WxpayAPI_php_v3/example/notify.php");
    $input->SetTrade_type("NATIVE");
    $input->SetProduct_id($forpayid);
    $result = $notify->GetPayUrl($input);

    //print_r($result);

    $url2 = $result["code_url"];


    $title = '微信支付';
    include template('pay');

}